﻿using System.Collections.Generic;
using JulMar.Windows.Mvvm;
using System.Windows.Input;
using System.Collections.ObjectModel;

namespace NathansMapInfoProjects.WindowManager.ViewModels
{
    /// <summary>
    /// View model for the list of open windows in Mapinfo.
    /// </summary>
    public class OpenWindowsViewModel : ViewModel
    {
        public OpenWindowsViewModel(IEnumerable<GroupViewModel> groups)
        {
            // Wire up commands for the view model.
            this.SortAcc = new RelayCommand(obj => SortGroupItems(SortOrder.Ascending));
            this.SortDes = new RelayCommand(obj => SortGroupItems(SortOrder.Descending));
            this.Refresh = new RelayCommand(parm => this.RefreshWindowList());
            this.Groups = new ObservableCollection<GroupViewModel>(groups);
        }


        /// <summary>
        /// Sorts each group in the tree view by sort order.
        /// </summary>
        private void SortGroupItems(SortOrder order)
        {
            foreach (var item in this.Groups)
            {
                GroupViewModel group = item;
                if (group != null)
                    group.SortItems(order);
            }
        }

        /// <summary>
        /// Refreshes the list of open windows.
        /// </summary>
        private void RefreshWindowList()
        {
            foreach (var item in this.Groups)
            {
                GroupViewModel group = item;
                if (group != null)
                    group.LoadChildren();
            }
        }

        public ObservableCollection<GroupViewModel> Groups { get; private set; }

        /// <summary>
        /// Command bound to by the view to sort the items in ascending order.
        /// </summary>       
        public ICommand SortAcc { get; private set; }

        /// <summary>
        /// Command bound to by the view to sort the items in descending order.
        /// </summary>
        public ICommand SortDes { get; private set; }

        /// <summary>
        /// The command bound to the view to refresh the tree view if something doesn't get updated.
        /// This can be removed in future versions once the code keeps track of everything correctly.
        /// </summary>
        public ICommand Refresh { get; private set; }
    }
}
